﻿using System;
using System.Linq;

namespace IGolovkine.AoA.Tcp
{
    public class TcpInboundTunnel : IDisposable
    {
        private readonly IDisposable _subscription;
        private readonly TcpListener _listener;

        private readonly Lazy<string> _description;

        public TcpInboundTunnel(IMessageChannel channel, int sourcePort, string remoteHost, int remotePort)
        {
            _description = new Lazy<string>(() => string.Format("Port Tunnel: {0} -> {1}:{2}", sourcePort, remoteHost, remotePort));

            _listener = new TcpListener(sourcePort);
            _subscription = _listener.Connections.Select(connection =>
                {
                    CorrelationId connectionId = CorrelationId.Next();
                    channel.Input.OnNext(new TcpConnectionInitiated(connectionId, remoteHost, remotePort));
                    return new TcpOutboundTunnel(channel, connection, connectionId);
                }).Subscribe();
        }


        public override string ToString()
        {
            return _description.Value;
        }


        public void Dispose()
        {
            _subscription.Dispose();
            _listener.Dispose();
        }
    }
}